/*
 * Copyright (c) 2006-2018, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2019-07-11     flybreak     the first version
 */

#include "tcpserver.h"
#include <ulog/ulog.h>
#include <string.h>

#define DBG_TAG   "tcpserv"

static struct tcpserver *serv;
static uint8_t buf[1024];

static void tcpserver_event_notify(tcpclient_t client, uint8_t event)
{
    int ret;
    switch (event)
    {
    case TCPSERVER_EVENT_CONNECT:
        LOGD(DBG_TAG, "client connect:%d", client->sock);
        break;
    case TCPSERVER_EVENT_RECV:
        ret = tcpserver_recv(client, buf, 1024, -1);
        if (ret > 0)
        {
            ret = tcpserver_send(client, buf, ret, 0);
        }
        break;
    case TCPSERVER_EVENT_DISCONNECT:
        LOGD(DBG_TAG, "client disconnect:%d", client->sock);
        break;
    default:
        break;
    }
}

int tcpserver(int argc, char *argv[])
{
    if (argc != 3)
    {
        LOGD(DBG_TAG, "Usage:./select_server [ip] [port]\n");
        return -1;
    }
    serv = tcpserver_create(argv[1], atoi(argv[2]));

    tcpserver_set_notify_callback(serv, tcpserver_event_notify);

    return 0;
}
#include "aos/cli.h"
ALIOS_CLI_CMD_REGISTER(tcpserver, tcpserver, server start);

int tcpserver_stop(int argc, char *argv[])
{
    tcpserver_destroy(serv);
    return 0;
}
#include "aos/cli.h"
ALIOS_CLI_CMD_REGISTER(tcpserver_stop, tcpserver_stop, tcpserver stop);
